package com.lanyou.esb.cook.proxy.redis.proxy.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.exceptions.JedisException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.cook.proxy.common.Constants4Redis;
import com.lanyou.esb.cook.proxy.entity.IfAvgResTimes;
import com.lanyou.esb.cook.proxy.redis.JedisPoolUtils;
import com.lanyou.esb.cook.proxy.redis.proxy.base.BaseStrJedisProxy;

/**
 * 接口平均响应时间Redis操作代理
 * 
 * @author Davey.wu
 */
public class IfAvgResTimesJedisProxy extends BaseStrJedisProxy<IfAvgResTimes> {

	public IfAvgResTimesJedisProxy() {
		this.setTimeOut(Constants4Redis.REDIS_TIMEOUT_IFAVGRESTIME);
	}

	@Override
	public long setex(String key, IfAvgResTimes value) throws JedisException,
			JsonProcessingException {
		String json = toJson(value);
		long result = 0;
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			String setResult = jedis.set(key, json);
			// 区间总响应时间增加
			jedis.incrByFloat(getNumKey(getKeyFromObject(value)),
					value.getAvgResTimes());
			// 区间总请求次数增加
			jedis.incrBy(getTimesKey(getKeyFromObject(value)), 1);
			if (STRING_SET_RESULT.equalsIgnoreCase(setResult)) {
				result = 1;
			}
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		return result;
	}

	@Override
	public String getKeyFromObject(IfAvgResTimes value) {
		// TODO Auto-generated method stub
		return value.getIfId() + KEY_SEPARATOR + value.getSection();
	}

	/**
	 * 获取区间总响应时间键
	 * 
	 * @param key
	 *            ：键
	 * @return
	 */
	public static String getNumKey(String key) {
		return key + KEY_SEPARATOR + Constants4Redis.SUFFIX_NUMBER;
	}

	/**
	 * 获取区间总请求次数键
	 * 
	 * @param key
	 *            ：键
	 * @return
	 */
	public static String getTimesKey(String key) {
		return key + KEY_SEPARATOR + Constants4Redis.SUFFIX_TIMES;
	}

	/**
	 * 接口平均响应时间
	 * 
	 * @param key
	 *            ：键
	 * @return
	 */
	public String getAsStr(String key) {
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return "";
		}
		boolean broken = false;
		try {
			result = jedis.get(key);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		return result;
	}

	public Map<String, Object> getGroup(String key) throws JsonParseException,
			JsonMappingException, JedisException, IOException {
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return null;
		}
		String numKey = this.getNumKey(key);
		String timesKey = this.getTimesKey(key);
		Map<String, Response<String>> response = new HashMap<>(3);
		boolean broken = false;
		try {
			Pipeline pipe = jedis.pipelined();
			response.put(key, pipe.get(key));
			response.put(numKey, pipe.get(numKey));
			response.put(timesKey, pipe.get(timesKey));
			pipe.sync();
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (response.isEmpty()) {
			return null;
		}
		Map<String, Object> result = new HashMap<>(3);
		IfAvgResTimes object = null;
		String value = response.get(key) != null ? response.get(key).get() : "";
		if (StringUtils.isBlank(value)) {
			return null;
		}
		object = this.fromJson(value);
		result.put(key, object);
		result.put(numKey, response.get(numKey) != null ? response.get(numKey)
				.get() : "");
		result.put(timesKey,
				response.get(timesKey) != null ? response.get(timesKey).get()
						: "");
		return result;
	}
}
